package org.nvframe.manager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.state.StateBasedGame;
import org.nvframe.camera.Camera;
import org.nvframe.component.render.AbstractRender;
import org.nvframe.event.EventService;
import org.nvframe.event.eventtype.RenderEvent;

/**
 * 
 * @author Nik Van Looy
 */
public class RenderManager {
	
	private static final RenderManager _instance = new RenderManager();

	public static RenderManager getInstance() {
		return _instance;
	}
	
	private SortedMap<Integer, ArrayList<AbstractRender>> components;

	private RenderManager() {
		components = new TreeMap<Integer, ArrayList<AbstractRender>>();
	}
	
	/**
	 * adds a render component with default priority
	 * 
	 * @param comp
	 */
	public void addComponent(AbstractRender comp) {
		addComponent(comp, 0);
	}
	
	/**
	 * adds a render component with a priority to the hashmap
	 * 
	 * @param comp
	 * @param priority
	 */
	public void addComponent(AbstractRender comp, int priority) {
		if(priority < 0)
			priority = 0;

		if(!components.containsKey(priority))
			components.put(priority, new ArrayList<AbstractRender>());
		
		components.get(priority).add(comp);
	}

	/**
	 * 
	 * @param comp
	 * @param priority 
	 */
	public void removeComponent(AbstractRender comp, int priority) {
		List<AbstractRender> renders = components.get(priority);
		
		if(renders.contains(comp))
			renders.remove(comp);
	}
	
	public void render (GameContainer gc, StateBasedGame sb, Graphics gr) {
		// make a copy to avoid ConcurrentModificationException
		Collection<ArrayList<AbstractRender>> renderCompCol = components.values();
		
		Camera camera = Camera.getInstance();
		
		camera.translateGraphics(gc);
		
		for(ArrayList<AbstractRender> renderComps : renderCompCol)
			for(AbstractRender renderComp : renderComps)
				EventService.getInstance().fireEvent(new RenderEvent(gc, sb, gr), renderComp.getOwner());
		
		camera.untranslateGraphics(gc);
		
		EventService.getInstance().fireEvent(new RenderEvent(gc, sb, gr), false);
	}

}
